﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace T.FAS.Runtime.Metadata.Dao
{
    using System.Data;
    using System.Reflection;
    using T.FAS.Runtime.Metadata.Entity;    
    using T.ServiceComponent.DAC.Service;
    using T.ServiceComponent.DataAccessEx.Core;
    using T.ServiceComponent.Error;

    public class TMetaDataDao : DaoService<TMetadata>
    {
        public TMetaDataDao(string db = "TFAS") : base()
        {           
            this.DBName = db;
        }

        public override string IDColumnName
        {
            get
            {
                return "ID";
            }
        }

        public override string TableName
        {
            get
            {
                return "Meta_BasicInfo";
            }
        }

        public override List<string> ExceptColumnName
        {
            get
            {
                return new List<string>()
                {
                    "CurrentVersion",
                    "ContentJSON",
                    "MetaDataJson",
                    //"DataID",
                    "Content",
                    "MetaDataManageInfos",
                    "MetaTypeName",
                    "ServiceSetTypeIDList",
                    "totalCount",
                    "Ext",
                    "PropertyChanged",
                    nameof(TMetadata.RefSchema),
                    nameof(TMetadata.TermList),
                    nameof(TMetadata.CurrSchemaEnitty),
                    "CheckOutMetaData",
                    "MetaDataDependencies"
                };
            }
        }

        public override Dictionary<string, object> GetDataMapping(TMetadata data)
        {
            var datas = base.GetDataMapping(data);
            datas.Remove("MetaDataStatus");
            datas.Add("MetaDataStatus", (int)(data.MetaDataStatus));
            datas.Remove("SourceType");
            datas.Add("SourceType", (int)(data.SourceType));

            return datas;
        }

        public override TMetadata ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            //if (row["SortCode"] == DBNull.Value)
            //{
            //    row["SortCode"] = "0";
            //}
            if (row["Ext1"] == DBNull.Value)
            {
                row["Ext1"] = "";
            }
            if (row["Ext2"] == DBNull.Value)
            {
                row["Ext2"] = "";
            }
            if (row["Ext3"] == DBNull.Value)
            {
                row["Ext3"] = "";
            }
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);

            myCol.Remove("MetaDataStatus");
            myCol.Remove("SourceType");

            var data = base.ConvertToObject(myCol, row);

            if (row["MetaDataStatus"] != null)
                data.MetaDataStatus = (MetaDataStatus)Enum.Parse(typeof(MetaDataStatus),
                                                Convert.ToString(row["MetaDataStatus"]));
            if (row["SourceType"] != null) { 
                data.SourceType = (MetaDataSourceType)Enum.Parse(typeof(MetaDataSourceType),
                                                Convert.ToString(row["SourceType"]));
            }

            return data;
        }

        #region 元数据基本信息

        public TMetadata GetMetaDataByIDOrCode(string idCode, string projectBranchId = "", bool isContainDelete = false) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = "";
            if (isContainDelete)
            {
                sqlCondition = "1=1";
            }
            else {
                sqlCondition = "MetaDataStatus<>5";
            }
            sqlCondition = string.Format("{0} AND (Meta_BasicInfo.ID=@IdCode OR Meta_BasicInfo.Code=@IdCode)", sqlCondition);
            paramsList.Add(this.DB.MakeInParam("@IdCode", TDbDataType.VarChar, idCode));
            string TenantId = UserUtil.GetCurrentUserTenantId();
            if (TenantId != "T") {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.TenantId=@TenantId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@TenantId", TDbDataType.VarChar, TenantId));
            }
            if (string.IsNullOrEmpty(projectBranchId) == false && projectBranchId!="Main")
            {
                sqlCondition = string.Format("{0} and (Meta_BasicInfo.ProjectBranchId=@ProjectBranchId Or Meta_BasicInfo.ProjectBranchId='Public') ", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchId));
            }
            string sql = string.Format(@"select {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,
               {0}.CurrentVersionID,{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, Meta_Version.Version as CurrentVersion,{0}.IsDeleted,{0}.Creator,
               {0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime ,Meta_TypeInfo.Name as MetaTypeName, {0}.SortCode, {0}.IsMultiLanguageSupport,{0}.Culture,{0}.DevLevelCode,{0}.SourceType,{0}.Ext1, {0}.Ext2, {0}.Ext3, 
               {0}.TenantId,Meta_BasicInfo.ProjectBranchId from {0}
            Left Join Meta_Version on Meta_Version.ID ={0}.CurrentVersionID LEFT JOIN Meta_TypeInfo on Meta_TypeInfo.ID = Meta_BasicInfo.MetaTypeID", TableName);
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1}", sql, sqlCondition), paramsList.ToArray());
            TMetadata basicInfo = null;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //if(ds.Tables[0].Rows.Count>1)throw new TException("FAS-Meta-1019", $"获取元数据({idCode})失败,存在多条！");
                basicInfo = ConvertToObject(base.Columns, ds.Tables[0].Rows[0]);

                if (ds.Tables[0].Rows[0]["CurrentVersion"] != DBNull.Value)
                {
                    basicInfo.CurrentVersion = Convert.ToString(ds.Tables[0].Rows[0]["CurrentVersion"]);
                }

                if (ds.Tables[0].Rows[0]["MetaTypeName"] != DBNull.Value)
                {
                    basicInfo.MetaTypeName = Convert.ToString(ds.Tables[0].Rows[0]["MetaTypeName"]);
                }
            }
            return basicInfo;
        }
        public TMetadata GetMetaDataByIDOrCodeWithDelete(string idCode, string projectBranchId)
        {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();           
            string sqlCondition = string.Format("(Meta_BasicInfo.ID=@IdCode OR Meta_BasicInfo.Code=@IdCode)");
            paramsList.Add(this.DB.MakeInParam("@IdCode", TDbDataType.VarChar, idCode));
            string TenantId = UserUtil.GetCurrentUserTenantId();
            if (TenantId != "T")
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.TenantId=@TenantId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@TenantId", TDbDataType.VarChar, TenantId));
            }
            if (string.IsNullOrEmpty(projectBranchId) == false && projectBranchId!="Main")
            {
                sqlCondition = string.Format("{0} and (Meta_BasicInfo.ProjectBranchId=@ProjectBranchId Or Meta_BasicInfo.ProjectBranchId='Public')", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchId));
            }
            string sql = string.Format(@"select {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,
               {0}.CurrentVersionID,{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, Meta_Version.Version as CurrentVersion,{0}.IsDeleted,{0}.Creator,
               {0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime ,Meta_TypeInfo.Name as MetaTypeName, {0}.SortCode, {0}.IsMultiLanguageSupport,{0}.Culture,{0}.DevLevelCode,{0}.SourceType,{0}.Ext1, {0}.Ext2, {0}.Ext3, 
               {0}.TenantId,Meta_BasicInfo.ProjectBranchId from {0} Left Join Meta_Version on Meta_Version.ID={0}.CurrentVersionID LEFT JOIN Meta_TypeInfo on Meta_TypeInfo.ID = Meta_BasicInfo.MetaTypeID", TableName);
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1}", sql, sqlCondition), paramsList.ToArray());
            TMetadata basicInfo = null;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 1) throw new TException("FAS-Meta-1019", $"获取元数据({idCode})失败,存在多条！");
                basicInfo = ConvertToObject(base.Columns, ds.Tables[0].Rows[0]);

                if (ds.Tables[0].Rows[0]["CurrentVersion"] != DBNull.Value)
                {
                    basicInfo.CurrentVersion = Convert.ToString(ds.Tables[0].Rows[0]["CurrentVersion"]);
                }

                if (ds.Tables[0].Rows[0]["MetaTypeName"] != DBNull.Value)
                {
                    basicInfo.MetaTypeName = Convert.ToString(ds.Tables[0].Rows[0]["MetaTypeName"]);
                }
            }
            return basicInfo;
        }

        /// <summary>
        /// 获取指定版本的元数据
        /// </summary>
        /// <param name="metaDataId">元数据ID</param>
        /// <param name="version">版本</param>
        /// <returns>元数据</returns>
        public TMetadata GetMetaDataByVersion(string metaDataId, string version)
        {
            var list = this.GetObjectsByFilter(string.Format("ID='{0}' and CurrentVersionID ='{1}'", metaDataId, version));
            if (list != null&& list.Count>0)
            {
                return list.FirstOrDefault() as TMetadata;
            }

            return null;
        }

        /// <summary>
        /// 通过元数据标识和元数据类型，获取元数据基本信息（不包含管理信息）
        /// </summary>
        /// <param name="idCode"></param>
        /// <param name="metaTypeID"></param>
        /// <returns></returns>
        public TMetadata GetRTPMetaDataBasicInfoByMetaDataID(string idCode, string metaTypeID)
        {
            TMetadata basicInfo = null;
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format(" (Meta_BasicInfo.ID=@IdCode OR Meta_BasicInfo.Code=@IdCode) AND MetaDataStatus<>5");
            paramsList.Add(this.DB.MakeInParam("@IdCode", TDbDataType.VarChar, idCode));
            if (!string.IsNullOrEmpty(metaTypeID))
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.MetaTypeID=@MetaTypeID", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@MetaTypeID", TDbDataType.VarChar, metaTypeID));
            }
            string sql = string.Format(@"select {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,
               {0}.CurrentVersionID,{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, '' as CurrentVersion,{0}.IsDeleted,{0}.Creator,
               {0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime ,'' as MetaTypeName, {0}.SortCode, {0}.IsMultiLanguageSupport,{0}.Culture,{0}.DevLevelCode,{0}.SourceType,{0}.Ext1, {0}.Ext2, {0}.Ext3, 
               {0}.TenantId,Meta_BasicInfo.ProjectBranchId from {0} ", TableName);
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1} ", sql, sqlCondition), paramsList.ToArray());

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                basicInfo = ConvertToObject(base.Columns, ds.Tables[0].Rows[0]);

            }
            return basicInfo;
        }
        /// <summary>
        /// 通过元数据标识和元数据类型，获取元数据基本信息（不包含管理信息）
        /// </summary>
        /// <param name="metaDataID"></param>
        /// <param name="metaTypeID"></param>
        /// <returns></returns>
        public TMetadata GetMetaDataBasicInfoByMetaDataID(string metaDataCode, string metaTypeID, string projectBranchId="", string dbType = "")
        {
            TMetadata basicInfo = null;
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format(" Meta_BasicInfo.Code=@Code AND MetaDataStatus<>5");
            paramsList.Add(this.DB.MakeInParam("@Code", TDbDataType.VarChar, metaDataCode));
            string TenantId = UserUtil.GetCurrentUserTenantId();
            if (TenantId != "T")
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.TenantId=@TenantId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@TenantId", TDbDataType.VarChar, TenantId));
            }
            if (string.IsNullOrEmpty(projectBranchId) == false && projectBranchId!="Main")
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.ProjectBranchId=@ProjectBranchId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchId));
            }
            if (!string.IsNullOrEmpty(metaTypeID))
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.MetaTypeID=@MetaTypeID", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@MetaTypeID", TDbDataType.VarChar, metaTypeID));
            }
            if (!string.IsNullOrEmpty(dbType))
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.Ext2=@DBType)", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@DBType", TDbDataType.VarChar, dbType));                
            }

            string sql = string.Format(@"select {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,
               {0}.CurrentVersionID,{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, Meta_Version.Version as CurrentVersion,{0}.IsDeleted,{0}.Creator,
               {0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime ,Meta_TypeInfo.Name as MetaTypeName, {0}.SortCode, {0}.IsMultiLanguageSupport,{0}.Culture,{0}.DevLevelCode,{0}.SourceType,{0}.Ext1, {0}.Ext2, {0}.Ext3, 
               {0}.TenantId,Meta_BasicInfo.ProjectBranchId from {0} Left Join Meta_Version on Meta_Version.ID={0}.CurrentVersionID LEFT JOIN Meta_TypeInfo on Meta_TypeInfo.ID = Meta_BasicInfo.MetaTypeID", TableName);                        
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1} ", sql, sqlCondition), paramsList.ToArray());

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                basicInfo = ConvertToObject(base.Columns, ds.Tables[0].Rows[0]);

                if (ds.Tables[0].Rows[0]["CurrentVersion"] != DBNull.Value)
                {
                    basicInfo.CurrentVersion = Convert.ToString(ds.Tables[0].Rows[0]["CurrentVersion"]);
                }

                if (ds.Tables[0].Rows[0]["MetaTypeName"] != DBNull.Value)
                {
                    basicInfo.MetaTypeName = Convert.ToString(ds.Tables[0].Rows[0]["MetaTypeName"]);
                }
            }
            return basicInfo;
        }
        
        /// <summary>
        /// 更新元数据时间戳
        /// </summary>
        /// <param name="metaDataID"></param>
        /// <param name="userName"></param>
        /// <param name="dateTime"></param>
        public void UpdateProjectMetaDataLastModifyTime(string metaDataID, string userName, DateTime dateTime)
        {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@MetaDataID", TDbDataType.VarChar, metaDataID));
            paramsList.Add(this.DB.MakeInParam("@LastModifier", TDbDataType.VarChar, userName));
            paramsList.Add(this.DB.MakeInParam("@LastModifyTime", TDbDataType.DateTime, dateTime));           
            this.DB.ExecSqlStatement("Update Meta_BasicInfo Set LastModifier=@LastModifier,LastModifyTime=@LastModifyTime Where ID=@MetaDataID", paramsList.ToArray());
        }

        public int UpdateMetaBasicInfo(IMetaData metadata) {
            string updateSql = string.Format("UPDATE meta_basicinfo SET Code = @Code, Name = @Name, ContentID = @ContentID, CurrentVersionID = @CurrentVersionID, DataID = @DataID, Ext1 = @Ext1, Ext2 = @Ext2, Ext3 = @Ext3, LastModifier = @LastModifier, LastModifyTime = @LastModifyTime,MetaDataStatus=@MetaDataStatus WHERE ID = @ID");

            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            if (string.IsNullOrEmpty(metadata.ProjectBranchID) == false && metadata.ProjectBranchID != "Main")
            {
                updateSql = string.Format("{0} and ProjectBranchID = @ProjectBranchID", updateSql);

                paramsList.Add(this.DB.MakeInParam("@ProjectBranchID", TDbDataType.VarChar, metadata.ProjectBranchID));
            }
            paramsList.Add(this.DB.MakeInParam("@ID", TDbDataType.VarChar, metadata.ID));
            paramsList.Add(this.DB.MakeInParam("@Code", TDbDataType.VarChar, metadata.Code));
            paramsList.Add(this.DB.MakeInParam("@Name", TDbDataType.VarChar, metadata.Name));
            paramsList.Add(this.DB.MakeInParam("@ContentID", TDbDataType.VarChar, metadata.ContentID));
            paramsList.Add(this.DB.MakeInParam("@CurrentVersionID", TDbDataType.VarChar, metadata.CurrentVersionID));
            paramsList.Add(this.DB.MakeInParam("@DataID", TDbDataType.VarChar, metadata.DataID));
            paramsList.Add(this.DB.MakeInParam("@Ext1", TDbDataType.VarChar, metadata.Ext1));
            paramsList.Add(this.DB.MakeInParam("@Ext2", TDbDataType.VarChar, metadata.Ext2));
            paramsList.Add(this.DB.MakeInParam("@Ext3", TDbDataType.VarChar, metadata.Ext3));
            paramsList.Add(this.DB.MakeInParam("@LastModifier", TDbDataType.VarChar, metadata.LastModifier));
            paramsList.Add(this.DB.MakeInParam("@LastModifyTime", TDbDataType.DateTime, metadata.LastModifyTime));
            paramsList.Add(this.DB.MakeInParam("@MetaDataStatus", TDbDataType.Int, (int)metadata.MetaDataStatus));

            return this.DB.ExecSqlStatement(updateSql, paramsList.ToArray());
        }
        
        #endregion

        #region 查询元数据列表
        public List<TMetadata> QueryMetaDatasByType(string metaTypeId, string projectBranchId) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format(@"MetaTypeID=@MetaTypeID and MetaDataStatus!=5 ");
            paramsList.Add(this.DB.MakeInParam("@MetaTypeID", TDbDataType.VarChar, metaTypeId));
            string TenantId = UserUtil.GetCurrentUserTenantId();
            if (TenantId != "T")
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.TenantId=@TenantId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@TenantId", TDbDataType.VarChar, TenantId));
            }
            if (string.IsNullOrEmpty(projectBranchId) == false && projectBranchId!="Main")
            {
                sqlCondition = string.Format("{0} and Meta_BasicInfo.ProjectBranchId=@ProjectBranchId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchId));
            }
            string sql = string.Format(@"SELECT {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,{0}.CurrentVersionID,
{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, {0}.IsDeleted,{0}.Creator,{0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime, {0}.SortCode, {0}.Ext1, {0}.Ext2, 
{0}.Ext3, {0}.TenantId, {0}.IsMultiLanguageSupport, {0}.Culture, {0}.DevLevelCode, {0}.SourceType,{0}.ProjectBranchId FROM {0}", TableName);
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1}", sql, sqlCondition), paramsList.ToArray());
            List<TMetadata> list = new List<TMetadata>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    list.Add(ConvertToObject(this.Columns, row));
                }
            }
            return list;
        }

        public List<IMetaData> GetMetaDatasByProjectBranchID(string projectBranchId, bool notWithNew) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format("Meta_BasicInfo.ProjectBranchId=@ProjectBranchId");
            paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchId));
            if (notWithNew) {
                sqlCondition = string.Format("{0} AND Meta_BasicInfo.MetaDataStatus!=0", sqlCondition);
            }
            string sql = string.Format(@"select {0}.ID,{0}.Code,{0}.Name,{0}.MetaTypeID,{0}.Owner,{0}.MetaSpaceID,{0}.DataID,{0}.ContentID,
               {0}.CurrentVersionID,{0}.MetaDataStatus,{0}.CheckOutUser,{0}.Depth, Meta_Version.Version as CurrentVersion,{0}.IsDeleted,{0}.Creator,
               {0}.CreateTime,{0}.LastModifier,{0}.LastModifyTime , {0}.SortCode, {0}.IsMultiLanguageSupport,{0}.Culture,{0}.DevLevelCode,{0}.SourceType,{0}.Ext1, {0}.Ext2, {0}.Ext3, 
               {0}.TenantId,Meta_BasicInfo.ProjectBranchId from {0}
            Left Join Meta_Version on Meta_Version.ID ={0}.CurrentVersionID ", TableName);
            var ds = this.DB.ExecuteDataSet(string.Format("{0} WHERE {1}", sql, sqlCondition), paramsList.ToArray());
            List<IMetaData> metadatas = new List<IMetaData>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows) {
                    TMetadata basicInfo = null;
                    basicInfo = ConvertToObject(base.Columns, row); 
                    if (row["CurrentVersion"] != DBNull.Value)
                    {
                        basicInfo.CurrentVersion = Convert.ToString(row["CurrentVersion"]);
                    }
                    metadatas.Add(basicInfo);
                }                
            }
            return metadatas;
        }
        #endregion

        public bool IsExistsByMetaDataID(string metadataCode, string metadataID, string projectBranchID)
        {
            string sql = string.Format(@"select Code from {0} where  MetaDataStatus <> 5 and Code='{1}' AND TenantId='{2}'  ", TableName, metadataCode, UserUtil.GetCurrentUserTenantId());
            //if (!string.IsNullOrEmpty(metaType))
            //{
            //    sql = string.Format(@"{0} AND MetaTypeID='{1}'", sql, metaType);
            //}
            //if (!string.IsNullOrEmpty(projectBranchID))
            //{
            //    sql = string.Format(@"{0} AND ProjectBranchID='{1}'", sql, projectBranchID);
            //}
            if (!string.IsNullOrEmpty(metadataID)) {
                sql = string.Format(@"{0} AND ID<>'{1}'", sql, metadataID);
            }
            var ds = this.DB.ExecuteDataSet(sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 更新元数据基本欣赏-应用集群类型
        /// </summary>
        /// <param name="metaDataId">元数据标识</param>
        /// <param name="Ext2">应用集群类型</param>
        /// <returns></returns>
        public int UpdateMetaDataStatus(string metaDataId, string projectBranchID, MetaDataStatus metaDataStatus)
        {
            var sql = string.Format("Update {0} set MetaDataStatus={1},LastModifyTime='{3}' where ID='{2}' AND ProjectBranchID='{4}'", TableName, (int)metaDataStatus, metaDataId,DateTime.Now, projectBranchID);
            return this.DB.ExecSqlStatement(sql);
        }
        /// <summary>
        /// 更新用户创建人
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="userName"></param>
        /// <param name="projectBranchID"></param>
        public void UpdateCreateUserID(string userID, string userName, string projectBranchID)
        {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@Creator", TDbDataType.VarChar, userName));
            paramsList.Add(this.DB.MakeInParam("@ProjectBranchID", TDbDataType.VarChar, projectBranchID));

            this.DB.ExecSqlStatement($"Update {TableName} Set Creator=@Creator WHERE ProjectBranchID=@ProjectBranchID", paramsList.ToArray());
        }
        public int DeleteMetaData(string metaDataId, string projectBranchID) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format("ID=@MetaDataID");
            paramsList.Add(this.DB.MakeInParam("@MetaDataID", TDbDataType.VarChar, metaDataId));
            
            if (string.IsNullOrEmpty(projectBranchID) == false && projectBranchID != "Main")
            {
                sqlCondition = string.Format("{0} and ProjectBranchId=@ProjectBranchId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchID));
            }
            string sql = string.Format(@"Delete From {0}", TableName);
            return this.DB.ExecSqlStatement(string.Format("{0} WHERE {1}", sql, sqlCondition), paramsList.ToArray());
        }

        public int UpdateMetaDataContentID(string metaDataId, string projectBranchID)
        {
            var sql = string.Format("Update {0} set ContentID='T' where ID='{1}' AND ProjectBranchID='{2}'", TableName, metaDataId, projectBranchID);
            return this.DB.ExecSqlStatement(sql);
        }

        public string GetMetaDataVersion(string metaDataId, string projectBranchID) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            string sqlCondition = string.Format("ID=@MetaDataID");
            paramsList.Add(this.DB.MakeInParam("@MetaDataID", TDbDataType.VarChar, metaDataId));

            if (string.IsNullOrEmpty(projectBranchID) == false && projectBranchID != "Main")
            {
                sqlCondition = string.Format("{0} and ProjectBranchId=@ProjectBranchId", sqlCondition);
                paramsList.Add(this.DB.MakeInParam("@ProjectBranchId", TDbDataType.VarChar, projectBranchID));
            }
            var ds = this.DB.ExecuteDataSet(string.Format("select CurrentVersionID From {0} WHERE {1}", TableName, sqlCondition), paramsList.ToArray());
            string CurrentVersionID = "";
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                CurrentVersionID = Convert.ToString(ds.Tables[0].Rows[0]["CurrentVersionID"]);
            }
            return CurrentVersionID;
        }

        public List<TMetadata> GetCheckInMetaData(string projectBranchID, string checkOutUserID) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@ProjectBranchID", TDbDataType.VarChar, projectBranchID));
            paramsList.Add(this.DB.MakeInParam("@CheckOutUserID", TDbDataType.VarChar, checkOutUserID));
            string sql = string.Format(@"select meta.ID,meta.Code,meta.Name,meta.MetaTypeID,Owner,MetaSpaceID,DataID,meta.ContentID,CurrentVersionID,MetaDataStatus,CheckOutUser,Depth, Meta_Version.Version as CurrentVersion,IsDeleted,meta.Creator,meta.CreateTime,meta.LastModifier,meta.LastModifyTime ,SortCode, IsMultiLanguageSupport,Culture,DevLevelCode,SourceType,Ext1, Ext2, Ext3, TenantId,meta.ProjectBranchId 
from {0} meta left join Meta_Version on Meta_Version.ID = meta.CurrentVersionID where MetadataStatus = 1 and meta.ProjectBranchID=@ProjectBranchID
and not exists(select 1 from meta_checkout checkout where meta.ProjectBranchID = checkout.ProjectBranchID and meta.ID = checkout.MetaDataID and checkout.CheckOutState=0 and checkOutUserID = @CheckOutUserID)", TableName);
            var ds = this.DB.ExecuteDataSet(sql, paramsList.ToArray());
            List<TMetadata> list = new List<TMetadata>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var data = ConvertToObject(this.Columns, row);
                    data.CurrentVersion = Convert.ToString(row["CurrentVersion"]);
                    list.Add(data);
                }
            }
            return list;
        }

        public string GetMetaDataID(string metadataCode, string projectBranchId) {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>() {
                this.DB.MakeInParam("@Code", TDbDataType.VarChar, metadataCode),
                this.DB.MakeInParam("@ProjectBranchID", TDbDataType.VarChar, projectBranchId)
            };
            var ds = this.DB.ExecuteDataSet("select ID from Meta_BasicInfo WHERE Code=@Code AND ProjectBranchID=@ProjectBranchID AND MetaDataStatus<>5",paramsList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) {
                return Convert.ToString(ds.Tables[0].Rows[0]["ID"]);
            }
            return null;
        }
    }
}
